<script setup>
import { ref, onMounted } from 'vue'
import api from '../api/comments_api.js'
import { ElMessage, ElMessageBox } from 'element-plus'
import { computed } from 'vue'

// ---------------------- 表格数据 ----------------------
const tableData = ref([])
const total = ref(0)

// ---------------------- 分页对象 ----------------------
const searchObj = ref({
  current: 1,
  limit: 10,
  productId: '',
  userId: ''
})

// ---------------------- 加载评论 ----------------------
const loadComments = async () => {
  try {
    const res = await api.page(searchObj.value)
    tableData.value = res.data || []
    total.value = res.count || 0
  } catch (error) {
    console.error(error)
    tableData.value = []
    total.value = 0
    ElMessage.error('加载评论失败')
  }
}

// ---------------------- 页面初始化 ----------------------
onMounted(async () => {
  await loadComments()
})

//----------------------- 查询 ----------------------
const handleSearch = async () => {
  searchObj.value.current = 1
  loadComments()
}

//----------------------- 分页 ----------------------
const handleCurrentChange = (val) => {
  searchObj.value.current = val
  loadComments()
}
const handleSizeChange = (val) => {
  searchObj.value.limit = val
  searchObj.value.current = 1
  loadComments()
}

//----------------------- 删除评论 ----------------------
const handleDelete = async (commentId) => {
  try {
    await ElMessageBox.confirm('确定要删除这条评论吗？', '提示', { type: 'warning' })
    await api.del(commentId)
    ElMessage.success('删除成功')
    loadComments()
  } catch (error) {
    if (error !== 'cancel') {
      console.error(error)
      ElMessage.error('删除失败')
    }
  }
}

//----------------------- 编辑评论 ----------------------
const editDialogVisible = ref(false)
const editForm = ref({})

const handleEdit = (row) => {
  editForm.value = { ...row }
  editDialogVisible.value = true
}
const cancelEdit = () => {
  editForm.value = {}
  editDialogVisible.value = false
}
const submitEdit = async () => {
  if (!editForm.value.content) {
    ElMessage.warning('评论内容不能为空')
    return
  }
  try {
    await api.edit(editForm.value)
    ElMessage.success('修改成功')
    editDialogVisible.value = false
    loadComments()
  } catch (error) {
    console.error(error)
    ElMessage.error('修改失败')
  }
}
//----------------------- 编辑评论照片----------------------
const handleEditUploadSuccess = (response, file) => {
  editForm.value.photo = response.data
  console.log('编辑评论图片上传成功:', response.data)
}


// ---------------------- 新增评论 ----------------------
const addWinVisible = ref(false)
const newComment = ref({})

const showAddDialog = () => {
  newComment.value = { productId: '', userId: '', content: '',photo:'' }
  addWinVisible.value = true
}
const addCancel = () => {
  newComment.value = {}
  addWinVisible.value = false
}
const addCommit = async () => {
  if (!newComment.value.productId || !newComment.value.userId || !newComment.value.content) {
    ElMessage.warning('请填写完整评论信息')
    return
  }
  try {
    await api.add(newComment.value)
    ElMessage.success('新增成功')
    await loadComments()
    addWinVisible.value = false
  } catch (error) {
    console.error(error)
    ElMessage.error('新增失败')
  }
}
//-----------------------新增评论照片-----------------
const handleAddUploadSuccess = (response, file) => {
  newComment.value.photo = response.data;
  console.log('新增商品图片上传成功:', response.data);
}
</script>

<template>
  <div style="padding: 20px;">
    <h2>评论列表</h2>

    <!-- 查询 -->
    <el-form :inline="true" :model="searchObj" style="margin-bottom: 10px;">
      <el-form-item label="商品ID">
        <el-input v-model="searchObj.productId" placeholder="请输入商品ID" clearable/>
      </el-form-item>
      <el-form-item label="用户手机号">
        <el-input v-model="searchObj.userId" placeholder="请输入用户手机号" clearable/>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="handleSearch">查询</el-button>
<!--        <el-button type="success" @click="showAddDialog">新增评论</el-button>-->
      </el-form-item>
    </el-form>

    <!-- 表格 -->
    <el-table :data="tableData" border style="width: 100%;">
      <el-table-column prop="commentId" label="评论ID" width="100"/>
      <el-table-column prop="productId" label="商品ID" width="100"/>
      <el-table-column prop="productName" label="商品名称" width="150"/>
      <el-table-column prop="userId" label="用户手机号" width="100"/>
      <el-table-column prop="content" label="评论内容"/>
      <el-table-column prop="commentTime" label="评论时间" width="180"/>
      <el-table-column prop="photo" label="实物照片" width="120">
        <template #default="scope">
          <img v-if="scope.row.photo" :src="scope.row.photo" style="width: 100px; height: 100px;"/>
        </template>
      </el-table-column>

      <!-- 操作列 -->
      <el-table-column label="操作" width="200">
        <template #default="scope">
<!--          <el-button type="primary" size="small" @click="handleEdit(scope.row)">编辑</el-button>-->
          <el-button type="danger" size="small" @click="handleDelete(scope.row.commentId)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <el-pagination
        v-model:current-page="searchObj.current"
        v-model:page-size="searchObj.limit"
        :total="total"
        :page-sizes="[10,20,30,40]"
        layout="total, sizes, prev, pager, next, jumper"
        @current-change="handleCurrentChange"
        @size-change="handleSizeChange"
    />

    <!-- 编辑评论弹窗 -->
    <el-dialog v-model="editDialogVisible" title="编辑评论" width="500px">
      <el-form :model="editForm" label-width="100px">
        <el-form-item label="商品ID">
          <el-input v-model="editForm.productId"/>
        </el-form-item>
        <el-form-item label="评论内容">
          <el-input v-model="editForm.content"/>
        </el-form-item>
        <el-form-item label="用户手机号">
          <el-input v-model="editForm.userId"/>
        </el-form-item>
        <el-form-item label="评论图片">
          <el-upload
              class="avatar-uploader"
              action="/api/upload/file"
              :show-file-list="false"
              :on-success="handleEditUploadSuccess"
          >
            <img v-if="editForm.photo" :src="editForm.photo" style="width: 100px; height: 100px"/>
            <img v-else src="@/assets/shop.png" style="width:100px" />
          </el-upload>
        </el-form-item>
      </el-form>

      <template #footer>
        <el-button @click="cancelEdit">取消</el-button>
        <el-button type="primary" @click="submitEdit">保存</el-button>
      </template>
    </el-dialog>


    <!-- 新增评论弹窗 -->
    <el-dialog v-model="addWinVisible" title="新增评论" width="500px">
      <el-form :model="newComment" label-width="100px">
        <el-form-item label="商品ID">
          <el-input v-model="newComment.productId" placeholder="请输入商品ID"/>
        </el-form-item>
        <el-form-item label="用户手机号">
          <el-input v-model="newComment.userId" placeholder="请输入用户ID"/>
        </el-form-item>
        <el-form-item label="评论内容">
          <el-input v-model="newComment.content" placeholder="请输入评论内容"/>
        </el-form-item>
        <el-form-item label="评论图片">
          <el-upload
              class="avatar-uploader"
              action="/api/upload/file"
              :show-file-list="false"
              :on-success="handleAddUploadSuccess"
          >
            <img v-if="newComment.photo" :src="newComment.photo" style="width: 100px; height: 100px"/>
            <img v-else src="@/assets/shop.png" style="width:100px" />
          </el-upload>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="addCancel">取消</el-button>
        <el-button type="primary" @click="addCommit">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<style scoped>
h2 {
  color: rgba(244, 64, 64, 0.35);
  margin-bottom: 20px;
}
</style>
